package com.yhy.common.log.interceptor;

import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * web的调用时间统计拦截器
 */
@Slf4j
public class WebInvokeTimeInterceptor implements HandlerInterceptor {

    private final ThreadLocal<StopWatch> invokeTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request,
                             @NonNull HttpServletResponse response,
                             @NonNull Object handler) throws Exception {
        log.debug("♦♦♦ 请求开始 URI [{}]", request.getRequestURI());
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        invokeTime.set(stopWatch);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(@NonNull HttpServletRequest request,
                           @NonNull HttpServletResponse response,
                           @NonNull Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request,
                                @NonNull HttpServletResponse response,
                                @NonNull Object handler, Exception ex) throws Exception {
        StopWatch stopWatch = invokeTime.get();
        stopWatch.stop();
        log.debug("♦♦♦ 请求结束 URI [{}], 耗时为: {}毫秒", request.getRequestURI(), stopWatch.getTime());
        invokeTime.remove();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
